package com.wctj.api.base.page.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wctj.api.base.page.dto.PageDTO;

import java.util.Collections;
import java.util.List;

/**
 * TODO DESCRIPTION
 *
 * @author zzl
 * @date 2022-01-06
 */
public class PageBuilder {

    private int currentPage;
    private int pageSize;
    private int totalPages;
    private int total;
    private List<?> list;
    private Object other;
    private PageBuilder() {
    }

    private PageBuilder(List<?> list, int total, int currentPage, int pageSize, int totalPages) {
        this.list = list;
        this.total = total;
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.totalPages = totalPages;
    }

    private PageBuilder(List<?> list, int total, int currentPage, int pageSize, int totalPages, Object other) {
        this.list = list;
        this.total = total;
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.totalPages = totalPages;
        this.other = other;
    }

    public static <T> PageDTO<T> empty(int currentPage, int pageSize) {
        return (PageDTO<T>) of(currentPage, pageSize).build();
    }

    public static <T> PageDTO<T> iPage(IPage<T> page) {
        return new PageDTO<>(page);
    }

    public static <T> PageDTO<T> page(List<T> list, int total, int currentPage, int pageSize) {
        return page(list, total, currentPage, pageSize, (int) Math.ceil((double) total / pageSize), null);
    }

    public static <T> PageDTO<T> page(List<T> list, int total, int currentPage, int pageSize, Object other) {
        return page(list, total, currentPage, pageSize, (int) Math.ceil((double) total / pageSize), other);
    }

    public static <T> PageDTO<T> page(List<T> list, int total, int currentPage, int pageSize, int totalPages, Object other) {
        return (PageDTO<T>) of(list, total, currentPage, pageSize, totalPages, other).build();
    }

    public static PageBuilder of(int currentPage, int pageSize) {
        return of(Collections.emptyList(), 0, currentPage, pageSize, 0, null);
    }

    private static PageBuilder of(List<?> list, int total, int currentPage, int pageSize, int totalPages, Object other) {
        return new PageBuilder(list, total, currentPage, pageSize, totalPages, other);
    }

    public PageBuilder list(List<?> list) {
        this.list = list;
        return this;
    }

    public PageBuilder total(int total) {
        this.total = total;
        return this;
    }

    public PageBuilder totalPages(int totalPages) {
        this.totalPages = totalPages;
        return this;
    }

    public PageDTO<?> build() {
        return new PageDTO<>(this.list, this.total, this.currentPage, this.pageSize, this.totalPages, this.other);
    }

}
